<script setup>
import { reactive, ref, getCurrentInstance, onBeforeMount } from 'vue'
import {
  firstCategoryAdd,
  GetCategory,
  ChildCategoryAdd,
  CategoryEdit,
  CategoryDel
} from '@/api/info'
const { proxy } = getCurrentInstance()
const categoryTreeRef = ref(null)
const data = reactive({
  tree_data: [
    // {
    //   text: '一级 1',
    //   children: [
    //     {
    //       text: '二级 1-1',
    //       children: [
    //         {
    //           text: '三级 1-1-1'
    //         }
    //       ]
    //     }
    //   ]
    // }
  ],
  defaultProps: {
    children: 'children',
    label: 'category_name' //text
  },
  sub_category: null,
  sub_category_data: {},
  button_loading: false,
  parent_category: '',
  parent_category_data: {}
})
const config = reactive({
  type: 'default',
  default: {
    title: '添加分类', // 标题
    parent_disabled: true, // 父级分类禁用/启用
    sub_disabled: true, // 子级分类禁用/启用
    sub_show: true, // 子级分类显示/隐藏
    clear: ['parent_category', 'sub_category']
  },
  first_category_add: {
    title: '一级分类添加', // 标题
    parent_disabled: false, // 父级分类禁用/启用
    sub_disabled: true, // 子级分类禁用/启用
    sub_show: false, // 子级分类显示/隐藏
    clear: ['parent_category', 'sub_category']
  },
  child_category_add: {
    title: '子级分类添加', // 标题
    parent_disabled: true, // 父级分类禁用/启用
    sub_disabled: false, // 子级分类禁用/启用
    sub_show: true,
    clear: ['sub_category'],
    create: ['parent_category']
  },
  parent_category_edit: {
    title: '父级分类编辑', // 标题
    parent_disabled: false, // 父级分类禁用/启用
    sub_disabled: true, // 子级分类禁用/启用
    sub_show: false,
    create: ['parent_category']
  },
  child_category_edit: {
    title: '子级分类编辑', // 标题
    parent_disabled: true, // 父级分类禁用/启用
    sub_disabled: false, // 子级分类禁用/启用
    sub_show: true,
    create: ['parent_category', 'sub_category']
  }
})
const handleNodeClick = (data) => {
  // console.log(data)
}
const handleCategory = (type, node_data) => {
  // console.log(type, node_data)
  // console.log(node_data, 'node_data')
  config.type = type === 'delete_category' ? 'default' : type
  if (type == 'child_category_edit') {
    data.parent_category_data = node_data.parent || null
    data.sub_category_data = node_data || null
    // console.log(data)
  } else {
    data.parent_category_data = node_data || null
  }
  // 删除内容，还原内容
  handleInputValue()
  // 二次弹窗提醒
  type == 'delete_category' && handleDeleteConfirm()
}
const handleInputValue = () => {
  const clearObj = config[config.type].clear
  // 获取还原数据的对象
  const createObj = config[config.type].create
  //执行删除动作
  if (clearObj && clearObj.length > 0) {
    clearObj.forEach((item) => {
      data[item] = ''
      // data.parent_category = "";
      // data.sub_category = ""
    })
  }
  // 执行还原动作
  if (createObj && createObj.length > 0) {
    createObj.forEach((item) => {
      data[item] = data[`${item}_data`].data.category_name
    })
  }
}
const handleSumbit = () => {
  if (config.type == 'first_category_add') {
    handleFirstCategoryAdd()
  }
  if (config.type == 'child_category_add') {
    handleChildCategoryAdd()
  }
  if (config.type == 'child_category_edit' || config.type == 'parent_category_edit') {
    handleCategoryEdit()
  }
}
const handleDeleteConfirm = async () => {
  proxy.$confirm('确认删除该分类吗？删除后将无法恢复', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    showClose: false, // 取消右上角关闭按钮
    closeOnClickModal: false, // 取消点击遮罩关闭 MessageBox
    closeOnPressEscape: false, // 取消按下ESC键关闭MessageBox
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        try {
          let res = await CategoryDel({ categoryId: data.parent_category_data.data.id })
          // 成功提示
          proxy.$message({
            message: res.message,
            type: 'success'
          })
          instance.confirmButtonLoading = false
          done()
          // 删除交互
          categoryTreeRef.value.remove(data.parent_category_data)
        } catch (error) {
          console.log(error)
          instance.confirmButtonLoading = false
          done()
        }
      } else {
        done()
      }
    }
  })
}
const handleCategoryEdit = async () => {
  if (data.parent_category == '' || data.sub_category == '') {
    const message = config.type === 'parent_category_edit' ? '父级' : '子级'
    proxy.$message.error(`${message}分类不能为空`)
    return false
  }
  // 按钮加载状态
  data.button_loading = true
  const node_parent = data.parent_category_data.data
  const node_sub = data.sub_category_data.data
  try {
    // 接口
    let res = await CategoryEdit({
      categoryName:
        config.type === 'parent_category_edit' ? data.parent_category : data.sub_category, // 分类名称参数
      id: config.type === 'parent_category_edit' ? node_parent.id : node_sub.id // 分类ID参数
    })
    // 清除加载状态
    data.button_loading = false
    // 成功提示
    proxy.$message({
      message: res.message,
      type: 'success'
    })
    // 同步更新树形菜单节点
    const node_date = config.type === 'parent_category_edit' ? node_parent : node_sub
    node_date.category_name = res.data.category_name
  } catch (error) {
    data.button_loading = false
  }
}
const handleFirstCategoryAdd = async () => {
  // 父级为空提示并阻止
  if (!data.parent_category) {
    proxy.$message.error('父级分类名称不能为空')
    return false
  }
  // 确定按钮状态，防止多次提交
  data.button_loading = true
  // 执行接口
  try {
    let res = await firstCategoryAdd({ categoryName: data.parent_category })
    console.log(res)
    if (res.resCode == 0) {
      data.button_loading = false
      proxy.$message({
        message: res.message,
        type: 'success'
      })
      // 父级分类删除文本
      data.parent_category = ''
      handleGetCategory()
    }
  } catch (error) {
    data.button_loading = false
  }
}
const handleChildCategoryAdd = async () => {
  // 子级分类名称为空时提示
  if (!data.sub_category) {
    proxy.$message.error('子级分类不能为空')
    return false
  }
  // 按钮加载状态
  data.button_loading = true
  try {
    let res = await ChildCategoryAdd({
      categoryName: data.sub_category,
      parentId: data.parent_category_data.data.id
    })
    // console.log(res)
    if (res.resCode == 0) {
      data.button_loading = false
      proxy.$message({
        message: res.message,
        type: 'success'
      })
      // 删除子级分类文本
      data.sub_category = ''
      // console.log(res.data, data.parent_category_data)
      categoryTreeRef.value.append(res.data, data.parent_category_data)
      // handleGetCategory()
    }
  } catch (error) {
    data.button_loading = false
  }
}
const handleGetCategory = async () => {
  let res = await GetCategory()
  if (res.resCode == 0) {
    data.tree_data = res.data || []
  }
}
onBeforeMount(() => {
  handleGetCategory()
})
</script>
<template>
  <el-button type="danger" @click="handleCategory('first_category_add')">添加一级分类</el-button>
  <hr class="spacing-hr" />
  <el-row :gutter="20">
    <el-col :span="7">
      <div class="category-list">
        <el-tree
          node-key="id"
          ref="categoryTreeRef"
          :data="data.tree_data"
          :props="data.defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button type="danger" @click="handleCategory('child_category_add', node)" round
                  >添加子级</el-button
                >
                <el-button
                  type="success"
                  @click="
                    handleCategory(
                      node.level == 1 ? 'parent_category_edit' : 'child_category_edit',
                      node
                    )
                  "
                  round
                  >编辑分类</el-button
                >
                <el-button @click="handleCategory('delete_category', node)" round>删除</el-button>
              </span>
            </div>
          </template>
        </el-tree>
      </div>
    </el-col>
    <el-col :span="17">
      <h4 class="column">{{ config[config.type].title }}</h4>
      <el-form label-width="100px">
        <el-form-item label="父级分类">
          <el-input
            style="width: 20%"
            v-model.trim="data.parent_category"
            :disabled="config[config.type].parent_disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="子级分类" v-if="config[config.type].sub_show">
          <el-input
            style="width: 20%"
            v-model.trim="data.sub_category"
            :disabled="config[config.type].sub_disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="danger" :loading="data.button_loading" @click="handleSumbit"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style lang="scss" scoped>
.spacing-hr {
  border: none;
  border-top: 1px solid #e9e9e9;
  margin: 30px 0;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.column {
  height: 44px;
  padding: 0 20px;
  margin-bottom: 30px;
  line-height: 44px;
  border-radius: 6px;
  background-color: #f3f3f3;
}
:deep(.el-tree-node__content) {
  height: auto;
  button {
    padding: 6px 12px;
    margin: 8px 3px;
    font-size: 12px;
    height: auto;
  }
}
</style>
